package com.hframe.typefilter;

import java.text.DecimalFormat;

/**
 *  将单精度浮点数转为字符串
 * @author heqian
 *
 */
public class FloatToString implements FilterRef<Object, Float> {
	String format = "0";

	public FloatToString() {
	}

	/**
	 * 将单精度浮点数转为字符串
	 * 
	 * @param digit
	 *            保留小数点的位数
	 */
	public FloatToString(int digit) {
		format = create(digit);
	}

	@Override
	public Object filter(Float object) {
		try {
			DecimalFormat fo = new DecimalFormat(format);
			return fo.format(object);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 将单精度浮点数转为字符串
	 * 
	 * @param digit
	 *            保留小数点的位数
	 */
	public static String format(Float object, int digit) {
		String format = create(digit);
		try {
			DecimalFormat fo = new DecimalFormat(format);
			return fo.format(object);
		} catch (Exception e) {
			return null;
		}
	}

	private static String create(int digit) {
		String format = "";
		for (int i = 0; i < digit; i++) {
			format += "0";
		}
		if (format.length() > 0)
			format = "0." + format;
		else
			format = "0";
		return format;
	}

}